<template>
  <div class="add-behavior">
    <CommonList
      class="list"
      :items="listItems"
      @use="onUse"
      @select="onSelect"
      title="选择要添加的行为:"
    ></CommonList>
    <div class="desc">
      {{ desc }}
    </div>
    <div class="buttons">
      <SButton @click="onAddBehavior">添加</SButton>
      <SButton @click="onCancel">取消</SButton>
    </div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, inject, ref } from 'vue';
import CommonList from '../common-list/list.vue';
import SButton from '@/ui-kit/button/button.vue';
import { ListItem } from '../common-list';
import pluginsStore from '../../../store/plugins';
import { ProvideKey } from '@/ui-kit/window';
import assetsStore from '../../../store/assets';
import { sceneAssistant } from '../../index';
import { IAssetObject } from '../../../store/types';

export default defineComponent({
  name: 'add-behavior',
  components: { SButton, CommonList },
  emits: [],
  props: {
    data: {
      type: String,
      default: '',
    },
  },
  setup(props, { emit }) {
    const desc = ref('');
    const listItems = computed(() => {
      const objectID = props.data;
      const asset: IAssetObject | null = assetsStore().getAsset(objectID);
      const behaviors = asset?.data.behaviors || [];


      const items: ListItem[] = [];
      ((pluginsStore().allBehaviors) as Array<sail.GameBehavior>).forEach((item) => {
        if (!behaviors.find(el => el === item.bundle)) {
          const { icon, name, desc, group } = item.info;
          items.push({
            icon, label: name, desc, group,
            data: item.bundle,
          });
        } else {
          console.log('has bundle : ', item.bundle);
        }
      });
      return items;
    });
    let curBehavior: ListItem | null = null;
    const closeDialog = inject(ProvideKey.CloseWindow, () => {});

    async function insertBehavior() {
      if (curBehavior) {
        const objectID = props.data;
        if (objectID) {
          sceneAssistant.addBehavior(objectID, curBehavior.data);
        }
      }
    }

    return {
      listItems,
      desc,
      async onUse(data: ListItem) {
        curBehavior = data;
        closeDialog();
        await insertBehavior();
      },
      onSelect(data: ListItem) {
        desc.value = data.desc;
        curBehavior = data;
      },
      onCancel() {
        closeDialog();
      },
      async onAddBehavior() {
        closeDialog();
        await insertBehavior();
      },
    };
  },
});
</script>
<style scoped lang="scss">
.add-behavior {
  padding: 5px;
  display: flex;
  flex-direction: column;
  flex: 1;

  .desc {
    text-align: left;
    height: 20px;
  }

  .list {
    flex: 1;
  }

  .buttons {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
  }
}
</style>
